#encoding:utf-8
from flask import Flask ,render_template,request,url_for,redirect,make_response,session,g
from flask_bootstrap import Bootstrap
from flask_httpauth import HTTPBasicAuth
from werkzeug.security import generate_password_hash, check_password_hash
import time,os,requests,os,json,sqlite3


from Crypto.Cipher import AES
import base64,codecs





app = Flask(__name__)
bootstrap = Bootstrap(app)
auth = HTTPBasicAuth()
app.config['SECRET_KEY'] = os.urandom(24)
app.config['BOOTSTRAP_SERVE_LOCAL'] = True

@app.before_request
def before_request():
    g.db = sqlite3.connect("./user.db")

@app.teardown_request
def teardown_request(exception):
    db = getattr(g, 'db', None)
    if db is not None:
        db.close()
users = {
    "wangyifan": generate_password_hash("hello"),
    "haojunyu": generate_password_hash("Honghuoshiwo"),
    "123": generate_password_hash("123")
}
@auth.verify_password
def verify_password(username, password):
    if username in users and \
            check_password_hash(users.get(username), password):
        return username

@app.route('/disk',methods=['POST', 'GET'])
def disk():
    if request.method == 'POST':   
        name=request.form['user']
        formpassword=request.form['password']#提取表单数据
        sql="select * from user where username = "+'"'+str(name)+'"'#拼接寻找用户名和密码的SQL语句
        find=g.db.execute(sql)#查询结果
        result=find.fetchall()
        if len(result) ==0:
            return render_template("baogao.html",gaosuyonghu="该用户名未注册")
        else:
            pass
        username=result[0][0]
        password=result[0][1]
        if  formpassword != password:
            return render_template("baogao.html",gaosuyonghu="密码错误")
        else:
            wz="./static/anquan/anquan/anquan/"+username
            filelist=os.listdir(wz)
            session['name']=username#设定cookies保存用户名和密码使其可以自动登录
            session['password']=password
            session['username']=username
            return  render_template("diskfile.html",filelist=filelist,username=username)
            #response=make_response(res)

            #return response
            #return render_template("diskfile.html",filelist=filelist,username=username)
        return render_template("disk.html")
        
    else:#不是post但是有cookie也可以校验
        try:
            name=session.get('name')
            password=session.get('password')
            formpassword=password
            if name!=None:
                sql="select * from user where username = "+'"'+str(name)+'"'#拼接寻找用户名和密码的SQL语句
                find=g.db.execute(sql)#查询结果
                
                result=find.fetchall()
                if len(result) ==0:
                    return render_template("baogao.html",gaosuyonghu="未注册")
                else:
                    pass
                username=result[0][0]
                password=result[0][1]
                if  formpassword != password:
                    return "密码已被修改请重新登陆"
                wz="./static"+"/anquan/anquan/anquan/"+username
                filelist=os.listdir(wz)
                return   render_template("diskfile.html",filelist=filelist,username=name)
            else:
                return render_template("disk.html")

            filelist=os.listdir(wz)
            return   render_template("diskfile.html",filelist=filelist,username=name)
        except:
            pass
        return render_template("disk.html")
@app.route('/')
def mainpage():
    return render_template("mainpage.html")



@app.route('/jiemi',methods=['GET', 'POST'])
def jm():
    if request.method == 'POST':
        key=str(request.form['key'])
        sjm=str(request.form['sjm'])
        word=str(request.form['word'])
        new_bytes = bytes(word[2:-1], encoding="utf-8")
        ciphertext = codecs.escape_decode(new_bytes, "hex-escape")[0]
        key=key.encode()
        sjm=sjm.encode()
        try:
            cipher = AES.new(key, AES.MODE_EAX, nonce=sjm)
            plaintext = cipher.decrypt(ciphertext)
        except:
            return "传入参数错误"
        return render_template("jiemi.html",xxx=str(plaintext.decode()))
    else:
        return render_template("jiemi.html")



@app.route('/jiami',methods=['GET', 'POST'])
def jm2():
    if request.method == 'POST':
        key=str(request.form['key'])
        sjm=str(request.form['sjm'])
        word=str(request.form['word'])
        ciphertext=word.encode('utf-8','strict')
        key = key.encode()
        sjm = bytes(sjm,encoding="utf-8")
        sjm = codecs.escape_decode(sjm, "hex-escape")[0]
        try:
            cipher = AES.new(key, AES.MODE_EAX,nonce=sjm)
            ciphertext, tag = cipher.encrypt_and_digest(ciphertext)
            return render_template("jiami.html",xxx=str(ciphertext))
        except:
            return "传入参数格式错误"
    else:
        return render_template("jiami.html")




@app.route("/tou")
def agent_show():
    # 获取用户代理信息
    user_agent = request.headers.get("User-Agent")
    # 使用HTML语言加工修饰
    message = "<h1>浏览器头信息</h1>\n<p>你的浏览器头信息是:</br> %s</p>" % user_agent
    return message
@app.route('/i', methods=['GET', 'POST'])
def insertuser():
    if request.method == 'POST':
        conn=sqlite3.connect('user.db')
        cursor=conn.cursor()
        cursor.execute('select  *  from  shegongku')
        a=cursor.fetchall()
        id1=len(a)+1
        name=request.form['name']
        age=request.form['age']
        sex=request.form['sex']
        homeaddress=request.form['homeaddress']
        QQ=request.form['QQ']
        IDcard=request.form['IDcard']
        school=request.form['school']
        xueli=request.form['xueli']
        wechat=request.form['wechat']
        telegram=request.form['telegram']
        work=request.form['work']
        fanzui=request.form['fanzui']
        relatives=request.form['relatives']
        phonenumber=request.form['phonenumber']
        #xueli=request.form['xueli']
        conn=sqlite3.connect('user.db')
        cursor=conn.cursor()
        data=(str(id1),name,age,sex,homeaddress,QQ,wechat,telegram,work,fanzui,relatives,phonenumber,xueli,school,IDcard)
        isql='insert  into  shegongku(id,name,age,sex,homeaddress,QQ,wechat,telegram,work,fanzui,relatives,phonenumber,xueli,school,IDcard)values'
        isql=isql+str(data)
        try:
            g.db.execute(isql)
        except:
            return "字段不合法"
        
        g.db.commit()
        return render_template("insert.html")
    else:
        return render_template("insert.html")
@app.errorhandler(404)
def page_not_found(e):
    return  render_template('404.html'),404
@app.errorhandler(500)
def page_wrong(e):
    return  render_template('500.html'),500
@app.route('/s', methods=['GET', 'POST'])
def selectuser():
    if request.method == 'POST':
        s=request.form['s']
        text=request.form['text']
        sql="select  *  from  shegongku  where  "+s+'="'+text+'"'
        results=g.db.execute(sql)
        results=results.fetchall()
        if len(results)!=0:
            return render_template("select.html",rec=results)
        else:
            return "没有相关数据"
    else:
        return render_template("select.html")
@app.route('/f1')
def f():
    filelist=os.listdir("./static/f")
    return   render_template("diskfile.html",filelist=filelist,username="static/f")
    
@app.route('/register',methods=['POST', 'GET'])
def register():
    if request.method == 'POST':   
        name=request.form['user']

        ###########################################
        cannotmkdir="~!@#$%^&*()_+-*/<>,[]\/"#不允许的文件名关键字
        for c in  cannotmkdir:#特殊字符
              for u in  name:#文件名
                    if   u==c:
                            tellusers="检测到特殊符号"+u+"请更换注册的用户名"
                            return render_template("baogao.html",gaosuyonghu=telluse)
                    else:
                            pass
########################处理特殊字符






        formpassword=request.form['password']#提取表单数据
        sql="select * from user where username = "+'"'+str(name)+'"'#拼接寻找用户名和密码的SQL语句
        find=g.db.execute(sql)#查询结果
        result=find.fetchall()
        if len(result) ==0:
            sql1='insert into user(username,password)values('
            sql3='"'+name+'"'+","+'"'+formpassword+'"'+')'
            sql=sql1+sql3
            g.db.execute(sql)
            g.db.commit()
            try:
                cj1="./static/anquan/anquan/anquan//"+name
                os.mkdir(cj1)
            except:
                return"数据库插入成功,但是没有创建文件夹"
            return render_template("baogao.html",gaosuyonghu="恭喜您,注册成功")
            
        else:
            return render_template("baogao.html",gaosuyonghu="该用户名已经注册")
    else:
        return render_template("disk.html")  
@app.route('/news',methods=['GET'])
def news():
   newlist=os.listdir("./static/news")
   listsend=[]
   for i in newlist:
      x=i.split('.txt',1)
      listsend.append(x[0])
   #x = txt.split("#", 1)
   return render_template("news.html",l=listsend)
@app.route('/upload',methods=['POST', 'GET'])
def uploadfile():
    if request.method == 'POST':
        try:    
            name=session.get('name')
            formpassword=session.get('password')
        except:
            return render_template("baogao.html",gaosuyonghu="您还未登录")
        #filename=request.form['filename']
        

        #name=request.form['user']
        #formpassword=request.form['password']#提取表单数据
        sql="select * from user where username = "+'"'+str(name)+'"'
        find=g.db.execute(sql)
        result=find.fetchall()
        if len(result)!=0:
            username=result[0][0]
            password=result[0][1]
            if name==username and formpassword==password:
                f = request.files['file']
                filename=f.filename
                print("文件名为:",filename)



                cannotmkdir="~!@#$%^&*()_+-*/<>,[]\/"#不允许的文件名关键字
                for c in  cannotmkdir:#特殊字符
                           for u in  filename:
                               if   u==c:
                                    tellusers="检测到特殊符号"+u+"请更换文件名"
                                    return render_template("baogao.html",gaosuyonghu=tellusers)
                               else:
                                    pass
                path="./static/anquan/anquan/anquan/"+username+"/"+filename
                try:
                    f.save(path)
                except:
                    return render_template("baogao.html",gaosuyonghu="存储失败,原因未知")
                return render_template("baogao.html",gaosuyonghu="上传成功")
            else:
                return render_template("baogao.html",gaosuyonghu="密码错误")
        else:
                        return render_template("baogao.html",gaosuyonghu="您还未注册")
    else:
        try:
            name=session.get('name')
            formpassword=session.get('password')
            if name==None and formpassword==None:
                return  render_template('nologin.html')
            else:
                pass
        except:
            return  render_template('nologin.html')
        return render_template("uploads1.2.html")
@app.route('/remove',methods=['POST', 'GET'])
def removefile():
    if request.method == 'POST':
        name=session.get('name')
        formpassword=session.get('password')#cookies获取登录信息
        if  name ==None and  formpassword==None:
            return  render_template('nologin.html')
        else:
            pass
        removefile=request.form['removefile']
        wz="./static/anquan/anquan/anquan/"+name
        try:  
                os.remove(os.path.join(wz,removefile))
                return render_template("baogao.html",gaosuyonghu="删除成功")
        except:
                return render_template("baogao.html",gaosuyonghu="文件不存在或者已经删除了!")
            
    else:
        return render_template("remove.html")
@app.route('/chat', methods=['GET', 'POST'])
def chat():
    if request.method == 'POST':
        rec=request.form['sendmessage']
        file=open("chat.txt","a",encoding="utf-8")
        file.write(str(rec))
        file.write("\n")
        file.close()
        file=open("chat.txt","r",encoding="utf-8")
        u=file.readlines()
        file.close()
    else:
       file=open("chat.txt","r+",encoding="utf-8")
       u=file.readlines()
       file.close()
    return render_template('chat.html',data=u)
@app.route("/ip")
def ip_show():
    # 获取用户代理信息
    ip = request.remote_addr
    # 使用HTML语言加工修饰
    url1="http://apis.juhe.cn/ip/ipNew"
    url2=url1+"?ip="+ip+"&key=a0dba57762a4c5f00362bc789744fee2&dtype=json"
    print(url2)
    response=requests.get(url2)
    content=response.content
    try:
       res=json.loads(content)
       allres=str(res['result']['Country']+res['result']['Province']+res['result']['City']+res['result']['Isp'])
    except:
       allres="未知"
    message="你的ip地址为:</br>"+ip+"</br>根据ip地址定位:</br>"+allres
    return render_template("baogao.html",gaosuyonghu=message)
@app.route("/<username>/<filename>")
def show_file(username,filename):
    name=session.get('name')
    formpassword=session.get('password')
    username=username
    filename=filename
    if username !=name:
        return render_template("baogao.html",gaosuyonghu="请先登录,再下载文件")
    else:
        sql="select * from user where username = "+'"'+str(name)+'"'#拼接寻找用户名和密码的SQL语句
        find=g.db.execute(sql)#查询结果
        result=find.fetchall()
        if len(result) ==0:
            return "未注册"
        else:
            pass
        username=result[0][0]
        password=result[0][1]
        if  formpassword != password:
            return "密码错误"
        pc="./anquan/anquan/anquan/"+name+"/"+filename
    return app.send_static_file(pc)

@app.route('/chat2', methods=['GET', 'POST'])
@auth.login_required
def chat2():
    if request.method == 'POST':
        rec=request.form['sendmessage']
        if  rec=="清除记录":
            file=open("chat2.txt","w+",encoding="utf-8")
            file.close()
            rec="历史记录被清楚了"
        else:
            pass
        file=open("chat2.txt","a",encoding="utf-8")
        file.write(str(format(auth.current_user()))+"在"+  str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) +"时说: "+str(rec))
        file.write("\n")
        file.close()
        file=open("chat2.txt","r",encoding="utf-8")
        u=file.readlines()
        file.close()
    else:
       file=open("chat2.txt","r+",encoding="utf-8")
       u=file.readlines()
       file.close()
    return render_template('chat.html',data=u)
@app.errorhandler(404)
def page_not_found(e):
    return  render_template('404.html'),404
@app.errorhandler(500)
def page_wrong(e):
    return  render_template('500.html'),500
if __name__ == '__main__':
    app.run(host="0.0.0.0",port=335,ssl_context=('server.crt','server.key'))